using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.Business;
using twistmachinev2.Entity;
using twistmachinev2.OPCUA;
using twistmachinev2.Repository;

namespace twistmachinev2
{
    public partial class FrmInformation : Form
    {
        private OpcUaConfigService _configService;
        private OPCUARepository _repository;
        private List<OpcUaNodeConfigEntity> _nodeList;
        private OpcUaNodeConfigEntity _currentNode;
        private OpcUaServerConfigEntity _currentServerConfig;
        private bool _isEditing = false;
        private bool _isEditingServer = false;

        public FrmInformation()
        {
            InitializeComponent();
            InitializeServices();
            InitializeUI();
        }

        private void InitializeServices()
        {
            try
            {
                // 初始化数据库连接
                _repository = new OPCUARepository();
                _configService = new OpcUaConfigService(_repository);

                // 检查是否需要从JSON迁移数据
                if (_configService.NeedMigration())
                {
                    _configService.MigrateFromJsonConfig();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化服务失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeUI()
        {
            // 初始化数据类型下拉框
            cmbDataType.Items.AddRange(new string[] { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid", "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode", "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue", "Variant", "DiagnosticInfo" });
            cmbDataType.SelectedIndex = 0;

            // 初始化访问级别下拉框
            cmbAccessLevel.Items.AddRange(new string[] { "None", "CurrentRead", "CurrentWrite", "CurrentReadOrWrite", "HistoryRead", "HistoryWrite", "HistoryReadOrWrite", "SemanticChange", "StatusWrite", "TimestampWrite" });
            cmbAccessLevel.SelectedIndex = 2; // CurrentReadOrWrite

            // 设置数值控件默认值
            numScanRate.Minimum = 100;
            numScanRate.Maximum = 60000;
            numScanRate.Value = 1000;
            numScanRate.Increment = 100;

            numSort.Minimum = 0;
            numSort.Maximum = 9999;
            numSort.Value = 0;

            // 初始化DataGridView
            InitializeDataGridView();

            // 绑定事件
            BindEvents();

            // 设置初始状态
            SetEditMode(false);
        }

        private void InitializeDataGridView()
        {
            dgvNodes.AutoGenerateColumns = false;
            dgvNodes.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvNodes.MultiSelect = false;
            dgvNodes.AllowUserToAddRows = false;
            dgvNodes.AllowUserToDeleteRows = false;
            dgvNodes.ReadOnly = true;

            // 添加列
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "NodeId", HeaderText = "节点ID", DataPropertyName = "NodeId", Width = 150 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "Name", HeaderText = "名称", DataPropertyName = "Name", Width = 120 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "DataType", HeaderText = "数据类型", DataPropertyName = "DataType", Width = 100 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "Group", HeaderText = "分组", DataPropertyName = "Group", Width = 80 });
            dgvNodes.Columns.Add(new DataGridViewCheckBoxColumn { Name = "IsSubscribed", HeaderText = "订阅", DataPropertyName = "IsSubscribed", Width = 60 });
            dgvNodes.Columns.Add(new DataGridViewCheckBoxColumn { Name = "IsEnabled", HeaderText = "启用", DataPropertyName = "IsEnabled", Width = 60 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "WriteFunction", HeaderText = "写入类型", DataPropertyName = "WriteFunction", Width = 60 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "ScanRate", HeaderText = "扫描频率", DataPropertyName = "ScanRate", Width = 80 });
            dgvNodes.Columns.Add(new DataGridViewTextBoxColumn { Name = "Description", HeaderText = "描述", DataPropertyName = "Description", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill });
        }

        private void BindEvents()
        {
            // 工具栏事件
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnRefresh.Click += BtnRefresh_Click;
            btnSave.Click += BtnSave_Click;
            btnImportExcel.Click += BtnImportExcel_Click;
            btnSearch.Click += BtnSearch_Click;
            txtSearch.KeyDown += TxtSearch_KeyDown;

            // DataGridView事件
            dgvNodes.SelectionChanged += DgvNodes_SelectionChanged;

            // 详情面板事件
            btnSaveNode.Click += BtnSaveNode_Click;
            btnCancel.Click += BtnCancel_Click;

            // 服务器配置事件
            btnSaveServer.Click += BtnSaveServer_Click;
            btnCancelServer.Click += BtnCancelServer_Click;

            // Tab切换事件
            tabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
        }

        private void FrmInformation_Load(object sender, EventArgs e)
        {
            LoadOpcUaConfigurations();
        }

        private void LoadOpcUaConfigurations()
        {
            try
            {
                LoadServerConfig();
                LoadNodeConfigs();
                UpdateStatusInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载服务器配置
        /// </summary>
        private void LoadServerConfig()
        {
            try
            {
                _currentServerConfig = _configService.GetServerConfig();
                if (_currentServerConfig != null)
                {
                    ShowServerConfigDetails(_currentServerConfig);
                }
                else
                {
                    // 创建默认配置
                    _currentServerConfig = new OpcUaServerConfigEntity
                    {
                        Id = 0,
                        ServerUrl = "opc.tcp://localhost:4840",
                        Username = "",
                        Password = "",
                        IsEnabled = true,
                        Remark = "默认OPC UA服务器配置",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    ShowServerConfigDetails(_currentServerConfig);
                }
            }
            catch (Exception ex)
            {
                // 使用默认配置
                Console.WriteLine($"加载服务器配置失败，使用默认配置: {ex.Message}");
                _currentServerConfig = new OpcUaServerConfigEntity
                {
                    Id = 0,
                    ServerUrl = "opc.tcp://localhost:4840",
                    Username = "",
                    Password = "",
                    IsEnabled = true,
                    Remark = "默认OPC UA服务器配置",
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };
                ShowServerConfigDetails(_currentServerConfig);
            }
        }

        /// <summary>
        /// 加载节点配置
        /// </summary>
        private void LoadNodeConfigs(string searchText = "")
        {
            try
            {
                _nodeList = _configService.GetAllNodes();

                if (!string.IsNullOrEmpty(searchText))
                {
                    _nodeList = _nodeList.Where(n =>
                        n.NodeId.Contains(searchText) ||
                        n.Name.Contains(searchText) ||
                        (n.Group ?? "").Contains(searchText) ||
                        n.Description.Contains(searchText)).ToList();
                }

                dgvNodes.DataSource = _nodeList;

                if (_nodeList.Count > 0)
                {
                    dgvNodes.Rows[0].Selected = true;
                    ShowNodeDetails(_nodeList[0]);
                }
                else
                {
                    ClearNodeDetails();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载节点配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateStatusInfo()
        {
            try
            {
                var nodeCount = _nodeList?.Count ?? 0;
                var subscribedCount = _nodeList?.Count(n => n.IsSubscribed) ?? 0;
                var enabledCount = _nodeList?.Count(n => n.IsEnabled) ?? 0;

                lblStatus.Text = "就绪";
                lblTotalCount.Text = $"总计: {nodeCount} | 订阅: {subscribedCount} | 启用: {enabledCount}";
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"错误: {ex.Message}";
            }
        }

        /// <summary>
        /// 刷新配置
        /// </summary>
        public void RefreshConfigurations()
        {
            LoadOpcUaConfigurations();
        }

        #region 事件处理

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            _currentNode = new OpcUaNodeConfigEntity
            {
                Id = 0,
                NodeId = "",
                Name = "",
                Description = "",
                DataType = "String",
                AccessLevel = "CurrentReadOrWrite",
                ScanRate = 1000,
                PropertyName = "",
                ObjectName = "",
                Group = "Default",
                Sort = 0,
                IsSubscribed = true,
                IsEnabled = true,
                Remark = "",
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                WriteFunction = 0
            };

            ShowNodeDetails(_currentNode);
            SetEditMode(true);
            txtNodeId.Focus();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dgvNodes.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要编辑的节点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SetEditMode(true);
            txtNodeId.Focus();
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvNodes.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要删除的节点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var node = dgvNodes.SelectedRows[0].DataBoundItem as OpcUaNodeConfigEntity;
            if (node == null) return;

            var result = MessageBox.Show($"确定要删除节点 '{node.Name}' 吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    _configService.RemoveNode(node.Id);
                    LoadNodeConfigs();
                    UpdateStatusInfo();
                    MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            RefreshConfigurations();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            //提示这个功能不能用
            MessageBox.Show($"此功能暂时不开放", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //try
            //{
            //    _configService.SaveNodes(_nodeList);
            //    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void BtnImportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开Excel导入窗体
                using (var frmImport = new FrmExcelImport())
                {
                    if (frmImport.ShowDialog() == DialogResult.OK)
                    {
                        // 导入成功后刷新数据
                        LoadNodeConfigs();
                        MessageBox.Show("Excel数据导入完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开Excel导入窗体失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            LoadNodeConfigs(txtSearch.Text.Trim());
            UpdateStatusInfo();
        }

        private void TxtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnSearch_Click(sender, e);
            }
        }

        private void DgvNodes_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvNodes.SelectedRows.Count > 0)
            {
                var node = dgvNodes.SelectedRows[0].DataBoundItem as OpcUaNodeConfigEntity;
                if (node != null)
                {
                    _currentNode = node;
                    ShowNodeDetails(node);
                }
            }

            // 更新按钮状态，确保有选中行时编辑和删除按钮可用
            SetEditMode(_isEditing);
        }

        private void BtnSaveNode_Click(object sender, EventArgs e)
        {
            if (!ValidateNodeInput())
                return;

            try
            {
                UpdateNodeFromUI();

                if (_currentNode.Id == 0)
                {
                    // 新增
                    _configService.AddNode(_currentNode);
                }
                else
                {
                    // 更新
                    _configService.UpdateNode(_currentNode);
                }

                LoadNodeConfigs();
                UpdateStatusInfo();
                SetEditMode(false);
                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            if (_currentNode != null)
            {
                ShowNodeDetails(_currentNode);
            }
            SetEditMode(false);
        }

        #endregion

        #region 辅助方法

        private void SetEditMode(bool isEditing)
        {
            _isEditing = isEditing;

            // 工具栏按钮状态
            btnAdd.Enabled = !isEditing;
            btnEdit.Enabled = !isEditing && dgvNodes.SelectedRows.Count > 0;
            btnDelete.Enabled = !isEditing && dgvNodes.SelectedRows.Count > 0;

            // 详情面板控件状态
            txtNodeId.ReadOnly = !isEditing;
            txtName.ReadOnly = !isEditing;
            txtDescription.ReadOnly = !isEditing;
            cmbDataType.Enabled = isEditing;
            cmbAccessLevel.Enabled = isEditing;
            numScanRate.ReadOnly = !isEditing;
            txtPropertyName.ReadOnly = !isEditing;
            txtObjectName.ReadOnly = !isEditing;
            txtGroup.ReadOnly = !isEditing;
            numSort.ReadOnly = !isEditing;
            txtRemark.ReadOnly = !isEditing;
            chkIsSubscribed.Enabled = isEditing;
            chkIsEnabled.Enabled = isEditing;
            txtWriteFunction.Enabled = isEditing;

            // 保存取消按钮面板
            panelButtons.Visible = isEditing;

            // DataGridView
            dgvNodes.Enabled = !isEditing;
        }

        private void ShowNodeDetails(OpcUaNodeConfigEntity node)
        {
            if (node == null)
            {
                ClearNodeDetails();
                return;
            }

            txtNodeId.Text = node.NodeId;
            txtName.Text = node.Name;
            txtDescription.Text = node.Description;
            cmbDataType.Text = node.DataType;
            cmbAccessLevel.Text = node.AccessLevel;
            numScanRate.Value = node.ScanRate;
            txtPropertyName.Text = node.PropertyName;
            txtObjectName.Text = node.ObjectName;
            txtGroup.Text = node.Group;
            numSort.Value = node.Sort;
            txtRemark.Text = node.Remark;
            chkIsSubscribed.Checked = node.IsSubscribed;
            chkIsEnabled.Checked = node.IsEnabled;
            txtWriteFunction.Text = node.WriteFunction.ToString();
        }

        private void ClearNodeDetails()
        {
            txtNodeId.Text = "";
            txtName.Text = "";
            txtDescription.Text = "";
            cmbDataType.SelectedIndex = 0;
            cmbAccessLevel.SelectedIndex = 2;
            numScanRate.Value = 1000;
            txtPropertyName.Text = "";
            txtObjectName.Text = "";
            txtGroup.Text = "";
            numSort.Value = 0;
            txtRemark.Text = "";
            chkIsSubscribed.Checked = true;
            chkIsEnabled.Checked = true;
            txtWriteFunction.Text = "0"; // 默认写入类型为0
        }

        private void UpdateNodeFromUI()
        {
            _currentNode.NodeId = txtNodeId.Text.Trim();
            _currentNode.Name = txtName.Text.Trim();
            _currentNode.Description = txtDescription.Text.Trim();
            _currentNode.DataType = cmbDataType.Text;
            _currentNode.AccessLevel = cmbAccessLevel.Text;
            _currentNode.ScanRate = (int)numScanRate.Value;
            _currentNode.PropertyName = txtPropertyName.Text.Trim();
            _currentNode.ObjectName = txtObjectName.Text.Trim();
            _currentNode.Group = txtGroup.Text.Trim();
            _currentNode.Sort = (int)numSort.Value;
            _currentNode.Remark = txtRemark.Text.Trim();
            _currentNode.IsSubscribed = chkIsSubscribed.Checked;
            _currentNode.IsEnabled = chkIsEnabled.Checked;
            _currentNode.UpdateTime = DateTime.Now;
            _currentNode.WriteFunction = int.TryParse(txtWriteFunction.Text.Trim(), out int writeFunction) ? writeFunction : 0;
        }

        private bool ValidateNodeInput()
        {
            if (string.IsNullOrWhiteSpace(txtNodeId.Text))
            {
                MessageBox.Show("节点ID不能为空", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtNodeId.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("节点名称不能为空", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtName.Focus();
                return false;
            }

            // 检查节点ID是否重复（新增时）
            if (_currentNode.Id == 0)
            {
                var existingNode = _nodeList?.FirstOrDefault(n => n.NodeId == txtNodeId.Text.Trim());
                if (existingNode != null)
                {
                    MessageBox.Show("节点ID已存在，请使用其他ID", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtNodeId.Focus();
                    return false;
                }
            }

            return true;
        }

        #endregion

        #region 服务器配置相关方法

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPageServer)
            {
                LoadServerConfig();
            }
        }

        private void BtnSaveServer_Click(object sender, EventArgs e)
        {
            if (!ValidateServerInput())
                return;

            try
            {
                UpdateServerConfigFromUI();
                _configService.SaveServerConfig(_currentServerConfig);
                MessageBox.Show("服务器配置保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存服务器配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnCancelServer_Click(object sender, EventArgs e)
        {
            if (_currentServerConfig != null)
            {
                ShowServerConfigDetails(_currentServerConfig);
            }
        }

        private void ShowServerConfigDetails(OpcUaServerConfigEntity serverConfig)
        {
            if (serverConfig == null)
            {
                ClearServerConfigDetails();
                return;
            }

            txtServerUrl.Text = serverConfig.ServerUrl ?? "";
            txtUsername.Text = serverConfig.Username ?? "";
            txtPassword.Text = serverConfig.Password ?? "";
            txtServerRemark.Text = serverConfig.Remark ?? "";
            chkServerEnabled.Checked = serverConfig.IsEnabled;
        }

        private void ClearServerConfigDetails()
        {
            txtServerUrl.Text = "";
            txtUsername.Text = "";
            txtPassword.Text = "";
            txtServerRemark.Text = "";
            chkServerEnabled.Checked = true;
        }

        private void UpdateServerConfigFromUI()
        {
            _currentServerConfig.ServerUrl = txtServerUrl.Text.Trim();
            _currentServerConfig.Username = txtUsername.Text.Trim();
            _currentServerConfig.Password = txtPassword.Text.Trim();
            _currentServerConfig.Remark = txtServerRemark.Text.Trim();
            _currentServerConfig.IsEnabled = chkServerEnabled.Checked;
            _currentServerConfig.UpdateTime = DateTime.Now;

            if (_currentServerConfig.Id == 0)
            {
                _currentServerConfig.CreateTime = DateTime.Now;
            }
        }

        private bool ValidateServerInput()
        {
            if (string.IsNullOrWhiteSpace(txtServerUrl.Text))
            {
                MessageBox.Show("服务器URL不能为空", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtServerUrl.Focus();
                return false;
            }

            // 验证URL格式
            if (!txtServerUrl.Text.Trim().StartsWith("opc.tcp://"))
            {
                MessageBox.Show("服务器URL格式不正确，应以 'opc.tcp://' 开头", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtServerUrl.Focus();
                return false;
            }

            return true;
        }

        #endregion

        /// <summary>
        /// 获取配置服务
        /// </summary>
        /// <returns>配置服务实例</returns>
        public OpcUaConfigService GetConfigService()
        {
            return _configService;
        }

        /// <summary>
        /// 获取数据库仓储实例
        /// </summary>
        /// <returns>数据库仓储实例</returns>
        public OPCUARepository GetRepository()
        {
            return _repository;
        }



        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        private void FrmInformation_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _configService?.Dispose();
                _repository?.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"释放资源时发生错误: {ex.Message}");
            }
        }

        private void btnRefresh_Click_1(object sender, EventArgs e)
        {

        }

        private void btnSaveNode_Click_1(object sender, EventArgs e)
        {

        }
    }
}
